<extend name="Public/base"/>
<block name="style">
    <link rel="stylesheet" href="__STATIC__/styles/video_view.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/video.min.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/bootstrap-table.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/bootstrap-select.min.css">
    <style type="text/css">
        input {
            width: 100%;
        }

        /*button {*/
            /*margin-top: 1em;*/
        /*}*/

        #publisher > h3 {
            text-align: center;
        }

        #status {
            color: blue;
            margin-bottom: 1em;
        }
        #publisher{
            outline: 1px dotted red;
        }

        .bs-bars{
            width: 75%;
        }
    </style>

</block>
<block name="content">
    <div id="toolbar">
        <button id="remove" class="btn btn-danger btn-flat" disabled>
            <i class="glyphicon glyphicon-remove"></i>删除
        </button>
        <!--<select class="selectpicker">-->
        <!--<option>所有回传人</option>-->
        <!--</select>-->
        <select id ='searchOption' class="selectpicker right pull-right">
            <option value="1">部门</option>
            <option value="2">回传人</option>
        </select>
    </div>
    <table id="table" data-toolbar="#toolbar">
    </table>
    <div class="modal fade" id="confirm_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">确认</h4>
                </div>
                <div class="modal-body">
                    确定要删除吗?
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger btn-flat confirmDel">删除</button>
                    <button type="button" class="btn btn-default btn-flat" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="video-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <button id="commBtn" type="button" class="btn-primary btn-flat pull-right">与其通信</button>

                    <!--<button id="settingBtn" type="button" class="btn-primary btn-flat pull-right">设置</button>-->
                    <h4 id="status" class="modal-title">播放视频</h4>

                </div>
                <div class="modal-body">
                    <video id="my-video" class="video-js" controls preload="auto" width="768" height="561"
                           poster="//vjs.zencdn.net/v/oceans.png" data-setup="{}">

                        <p class="vjs-no-js">
                            查看视频请开启Javascript, 需要升级到
                            <a href="http://videojs.com/html5-video-support/" target="_blank">支持HTML5 视频</a>
                            的浏览器
                        </p>
                    </video>
                    <div id="publisher" >
                        <h3>If your browser supports streaming, you'll<br>see the recorded video here.</h3>
                    </div>
                    <!--<div id="publisher"></div>-->
                </div>
            </div>
        </div>
    </div>


</block>

<block name="script">
    <script src="__STATIC__/scripts/vendors/bootstrap-select.min.js"></script>
    <script src="__STATIC__/scripts/vendors/bootstrap-table.js"></script>
    <script src="__STATIC__/scripts/vendors/video.min.js"></script>
    <script src="__STATIC__/scripts/vendors/videojs.ie8.min.js"></script>
    <script src="__STATIC__/scripts/vendors/sortable-jquery.binding.js"></script>
    <script src="__STATIC__/scripts/vendors/Sortable.min.js"></script>
    <script src="__STATIC__/scripts/vendors/videojs-contrib-hls.min.js"></script>
    <!--<script src="//nos.netease.com/vod163/nePublisher.min.js"></script>-->
    <script src="//cdn.bootcss.com/swfobject/2.2/swfobject.min.js"></script>
    <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/4.0.2/videojs-contrib-hls.min.js"></script>-->
    <script>


        function startPublish(liveName, videoURL){
            console.log("starting");
            var publisher = $('#publisher')[0];
            var options = getOptions(liveName, videoURL);
            publisher.setOptions(options);
            publisher.start();
        }

        function stopPublish(){
            var publisher = $('#publisher')[0];
            publisher.stop();
        }


        function getOptions(streamName, serverUrl){
            var fps = 30, intervalSecs = 3;
            return {
                serverURL: serverUrl
                , streamName: streamName
//                , streamKey: $form.find('#streamKey').val()
//                , audioCodec: 'Speex'
                , audioCodec: "{:C('AUDIO_TYPE')}"

                , streamWidth: 220
                , streamHeight: 140
                , streamFPS: fps
                , keyFrameInterval: fps * intervalSecs
                , bandwidth: 1500 * 1024 * 8
                , videoQuality: 5
                , embedTimecode: true
                , timecodeFrequency: 1000
            }
        }

        function initSWF(){
            var swfVersionStr = "11.4.0"
                    , xiSwfUrlStr = "playerProductInstall.swf"
                    , flashvars = {}
                    , params = {}
                    , attributes = {};

            params.allowscriptaccess = "sameDomain";
            params.allowfullscreen = "true";
            params.wmode = 'transparent';
            attributes.id = "publisher";
            attributes.name = "Publisher";
            attributes.align = "middle";
            swfobject.embedSWF(
                    "__STATIC__/assets/publisher/publisher.swf", "publisher", "220", "140",
                    swfVersionStr, xiSwfUrlStr,
                    flashvars, params, attributes,
                    function(embedEvent) {
                        if (embedEvent.success) {

                            setTimeout(function() {
                                embedEvent.ref.setOptions({
                                    jsLogFunction: "console.log",
                                    jsEmitFunction: "handleEmit" }
                                )
                            }, 2000);
                            updateStatus("Configure your stream, then press start.");
                            var publisher = $('#publisher')[0];
                            publisher.style.visibility="hidden";
                        }
                    }
            );

            $('.stop-btn').on('click', function(event) {
                event.preventDefault();
                var publisher = $('#publisher')[0];
                publisher.stop();
            })
        }

        function handleEmit(event) {
            switch(event.kind) {
                case "connect":
                case "disconnect":
                case "publish":
                case "status":
                case "error":
//                    if(event.kind =='connect'){
//                        var publisher = $('#publisher')[0];
//                        publisher.hide();
//                    }
                    if(event.code ==110){
                        var publisher = $('#publisher')[0];
                        publisher.style.visibility="hidden";
//                        var publisher = $('#publisher')[0];
//                        publisher.hide();
                    }
                    console.log("got event", new Date, event);
                    updateStatus(event.message);
                    break;
                default:

                    console.log(new Date, event);
            }

        }

        function updateStatus(message) {

        }




        var $table = $('#table');
        var $remove = $('#remove');
        var $videoModal = $('#video-modal');
        var $settingModal = $('#setting-modal');
        var tableHelper;
//        var $my_video;
        var $my_video = videojs('my-video');
        var $confirmModal = $('#confirm_modal');
        var $confirmDel = $('.confirmDel');
        var $commBtn = $('#commBtn');
        var $settingBtn = $('#settingBtn');
        var commStatus = 0;//喊话通信状态 0：初始化 1：连接中 2：已连接
        var liveName;
        var videoURL;
        var chat_key_pre = "{:C('IM_CHAT_KEY')}";
        var other_chat_id;
        var other_user_id;


        function changeStatus(status){
            commStatus = status;
            switch(commStatus){
                case 0:
                    $commBtn.text('与其通信');
                    $commBtn.show();
                    $('#status').text('播放视频');
                    break;
                case 1:
                    $commBtn.hide();
                    $('#status').text('语音连接中...');
                    break;
                case 2:
                    $('#status').text('已连接，可通话');
                    $commBtn.text('关闭通话');
                    $commBtn.show();
                    break;
            }
        }



        $videoModal.on('hide.bs.modal',function () {
            $my_video.width = 0;
            $my_video.height = 0;
            stopPublish();
            changeStatus(0);
//            commStatus = 0;
            $table.bootstrapTable('refresh');

            var publisher = $('#publisher')[0];
            publisher.style.visibility="hidden";
        });

        var TableHelper = function(){
            var oTableHelper = new Object();

            oTableHelper.selections = [];

            oTableHelper.init = function(){
                $table.bootstrapTable({
                    formatLoadingMessage: function () {
                        return '正在努力地加载数据中，请稍候……';
                    },
                    formatRecordsPerPage: function (pageNumber) {
                        return '每页显示 ' + pageNumber + ' 条记录';
                    },
                    formatShowingRows: function (pageFrom, pageTo, totalRows) {
                        return '显示第 ' + pageFrom + ' 到第 ' + pageTo + ' 条记录，总共 ' + totalRows + ' 条记录';
                    },
                    formatSearch: function () {
                        return '搜索';
                    },
                    formatNoMatches: function () {
                        return '没有找到匹配的记录';
                    },
                    formatPaginationSwitch: function () {
                        return '隐藏/显示分页';
                    },
                    formatRefresh: function () {
                        return '刷新';
                    },
                    formatToggle: function () {
                        return '切换';
                    },
                    formatColumns: function () {
                        return '列';
                    },
                    responseHandler:function(res){
                        return res;
                    },
                    url:"{:U('realtimeList')}",
                    method:'get',
                    striped:true,
                    cache:false,
                    pagination:true,
                    sortable:false,
                    sortOrder:'asc',
                    sidePagination:'server',
                    queryParams:oTableHelper.queryParams,
                    pageNumber:1,
                    pageSize:10,
                    pageList:[10,20,50],
                    uniqueId:'real_time_id',
                    search:true,
                    height:getHeight(),

                    columns:[
                        {
                            checkbox:true,
                            align:'center'
                        },
                        {
                            field: 'video_url',
                            title: '视频',
                            align: 'center',
                            formatter: function (value) {
                                return '<a href="javascript: void 0" value="'+ "{:C('PRE_VIDEO_URL')}" +value+'" class="title glyphicon glyphicon-play-circle" aria-hidden="true"></a>';
                            },
                            events: operateEvents
                        },
                        {
                            field: 'user_name',
                            title: '回传人',
                            align: 'center',
                        },
                        {
                            field:'org_name',
                            title:'部门',
                            align:'center',
                        },
                        {
                            field: 'add_time',
                            title: '回传时间',
                            align: 'center'
                        },
                        {
                            field: 'position',
                            title: '地址',
                            align: 'center'
                        }
                    ]
                });


                $(window).resize(function () {
                    $table.bootstrapTable('resetView', {height:getHeight()});
                });

                $table.on('check.bs.table uncheck.bs.table ' +
                        'check-all.bs.table uncheck-all.bs.table', function () {
                    $('#remove').prop('disabled', !$table.bootstrapTable('getSelections').length);

                    // save your data, here just save the current page
                    oTableHelper.selections = oTableHelper.getIdSelections();
                    // push or splice the selections if you want to save all data selections
                });





                $table.on('expand-row.bs.table', function (e, index, row, $detail) {
                    if (index % 2 == 1) {
                        $detail.html('Loading from ajax request...');
                        $.get('LICENSE', function (res) {
                            $detail.html(res.replace(/\n/g, '<br>'));
                        });
                    }
                });


            };

            oTableHelper.queryParams = function(params){
                var temp = {
                    limit:params.limit,
                    offset:params.offset,
                    search:params.search,
                    searchOption:$("#searchOption").val()
                };
                return temp;
            };

            oTableHelper.getIdSelections = function(){
                return $.map($table.bootstrapTable('getSelections'), function (row) {
                    return row.real_time_id;
                })
            };

            oTableHelper.refresh = function(){
                $table.bootstrapTable('refresh');
            };

            return oTableHelper;
        };



        window.operateEvents = {
            'click .title': function (e, value, row, index) {
//                                            var publisher = $('#publisher')[0];
//                            $('#publisher').attr('visibility', 'hidden');
                $videoModal.modal('show');
//                $my_video.src("{:C('PRE_VIDEO_URL')}" + value);
//                $my_video.play();
//                $my_video.hls("{:C('PRE_VIDEO_URL')}" + value);

                other_user_id = row.user_id;
                other_chat_id = chat_key_pre + other_user_id;
//                $my_video = videojs('my-video', {}, function () {
//                    videojs.log('player is ready');
//                    this.src({
//                        src: value,
//                        type:'rtmp/mp4'
//                    });
//                });
                $my_video.src(
                    {
                        src: value,
                        type:'rtmp/mp4'
//                        withCredentials:true
                    }
                );
                $my_video.play();
            },
        };

        function getHeight() {
            return $("#right").height() - 25 - $('#myTabs').outerHeight();
        }

        $(function () {
            initIM();
            initSWF();
            tableHelper = new TableHelper();
            tableHelper.init();


            $remove.click(function () {
                $confirmModal.modal('show');
            });

            $videoModal.on('hide.bs.modal', function () {
               $my_video.reset();
            });


            $confirmDel.click(function(){
                $confirmModal.modal('hide');

                    $.post({
                        url:"{:U('delete')}",
                        data:{
                            selectedIds : tableHelper.selections
                        },
                        success:function(data){
                            if(data.status == 1){
                                layer.msg('删除成功');
                                tableHelper.refresh();
                            }else{
                                layer.msg(data.msg);
                            }
                        }
                    });

            });

            $settingBtn.click(function () {
                $settingModal.modal('show');
            });


            $commBtn.click(function () {
                //初始状态，建立通信
                if(commStatus == 0){
                    $.get(
                        "{:U('connect')}",
                        function (data) {
                            if (data.state == 1){
                                var pullUrl = data.pullUrl;

                                if(chatSocket && chatSocket.readyState == WebSocket.OPEN){
                                    var msg = new Object();
                                    msg.cmd = '2';
                                    msg.too = other_chat_id;
                                    msg.type = 1;
                                    msg.body = new Object();
                                    msg.body.msg = pullUrl;
                                    msg.body.type = 2;
                                    chatSocket.send(JSON.stringify(msg));
                                }else{
                                    layer.msg('socket连接断开，刷新页面以重试');
                                }
//                                var item = data.data[0];
//                                liveName = item.liveName;
//                                videoURL = item.videoURL;
                                liveName = data.streamName;
                                videoURL = data.videoUrl;
                                changeStatus(1);
//                                startPublish(liveName, videoURL);
                            }
                        }
                    );
                }else if(commStatus == 2){
                    //建立通信成功后，断开连接
                    $.get(
                        "{:U('close')}",
                        function (data) {

                        }
                    );
                    stopPublish();
                    changeStatus(0);

                }

            });



            $(window).resize(function () {
                setTimeout(function () {
                    $table.bootstrapTable('resetView', {
                        height: getHeight()
                    });
                }, 100);
            });
            /**
             * 这是将视频设为可拖动排序的部分
             */
            $('#videos').sortable({
                //排序时动画during 150ms
                animation: 150,
                //只有在‘备注’的区域可以被拖动
                handle: '.addition'
            });


            $('.fixed-table-container').addClass('box box-primary');



            /**
             * 定制的播放/暂停按钮
             */
            $('.custom-control').click(function () {
                var $this = $(this);
                //通过data-value找到video的index
                var index = $this.attr('data-value');
                /**
                 * 重要，一个页面有多个视频时，若要手动控制视频，需要每个video有不同id
                 */
                var video_instance = videojs('video-' + index);
                //判断现在是播放还是暂停
                if($this.hasClass('glyphicon-pause')) {
                    $this.removeClass('glyphicon-pause');
                    $this.addClass('glyphicon-play');
                    video_instance.pause();
                } else {
                    $this.removeClass('glyphicon-play');
                    $this.addClass('glyphicon-pause');
                    video_instance.play();
                }
            });

        });


    </script>
</block>

<block name="im_script">
    <script>

        var chatSocket;
        var chat_id = $('input[name=chat_id]').val();



        function initIM(){
            chatSocket = new WebSocket("{:C('IM_URL')}");
            chatSocket.onopen = function(event){
                var msg = new Object();
                msg.cmd = 0;
                msg.userid = chat_id;
                chatSocket.send(JSON.stringify(msg));
            };

            chatSocket.onmessage = function(event){
                var msg = JSON.parse(event.data);
                if(msg.cmd == 2){
//                    if(msg.type == 1){
                        if(msg.body && msg.body.type == 3){
                            var publisher = $('#publisher')[0];
                            publisher.style.visibility="visible";
                            startPublish(liveName, videoURL);
                            changeStatus(2);
                        }

//                    }
                }
                console.log(event.data);
            }

        }
    </script>
</block>